﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore.Storage;
using Sale.Api.Application.Command.ClientPrice;
using Sale.Api.Application.工单.Command.Client;
using Sale.Domain;
using Sale.ErrorCode;
using Sale.Infrastructure.Implement;

namespace Sale.Api.Application.工单.Handler.Client
{
    public class UpdateClinentHandler : IRequestHandler<UpdateClinentCommand, ApiResult<int>>
    {
        private readonly ILogger<UpdateClinentHandler> logger;
        private readonly IMapper mapper;
        private readonly DatabaseContext db;

        public UpdateClinentHandler(ILogger<UpdateClinentHandler> logger,IMapper mapper,DatabaseContext db)
        {
            this.logger = logger;
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<ApiResult<int>> Handle(UpdateClinentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var client = db.SqlSugar.Queryable<ClientModel>().Where(x => x.ClientId == request.ClientId).First();
            client = mapper.Map(request, client);
            int r = await db.SqlSugar.Updateable(client).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "客户修改成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "客户修改失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
